<template>
  <div class="ptz-block" :style="cameraData.flvUrl == ''  ? 'color: #d8d9da' : 'cursor: pointer;'">
    <!--    <el-progress class="mic-level-bar" :percentage="level" :text-inside="true" v-if="ws"></el-progress>-->
    <div class="ptz-cell ptz-up" @mousedown="ptzControl('up')" @mouseup="ptzControl('stop')" command="up"
         title="上">
      <el-icon>
        <ArrowUpBold/>
      </el-icon>
    </div>
    <!--    <div class="ptz-cell ptz-upright" @mousedown="ptzControl('upright')" @mouseup="ptzControl('stop')"-->
    <!--         command="upright" title="左上">-->
    <!--      <el-icon>-->
    <!--        <ArrowUpBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <!--    <div class="ptz-cell ptz-upleft" @mousedown="ptzControl('upright')" @mouseup="ptzControl('stop')"-->
    <!--         command="upleft" title="右上">-->
    <!--      <el-icon>-->
    <!--        <ArrowUpBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <div class="ptz-cell ptz-left" @mousedown="ptzControl('left')" @mouseup="ptzControl('stop')"
         command="left" title="左">
      <el-icon>
        <ArrowLeftBold/>
      </el-icon>
    </div>
    <div class="ptz-center"
         :style="cameraData.flvUrl == '' || cameraData.flvUrl != 'camera-ball' ? 'background-color: #d8d9da' : ''"
         title="长按通话，松开挂断">
      <el-icon @mousedown.prevent="talkStart()" @mouseup.prevent="talkStop()">
        <Microphone :color="ws ? '#51f32d':'#968c8c'"/>
      </el-icon>
      <!--      <el-icon @click="talkStart">-->
      <!--        <Microphone :color="ws ? '#51f32d':'#968c8c'"/>-->
      <!--      </el-icon>-->

      <!--      <el-icon @mousedown.prevent="clickStartVoiceTalk()" @mouseup.prevent="clickStopVoiceTalk()"-->
      <!--               @mouseleave="">-->
      <!--        <Microphone :color="control ? '#51f32d':'#968c8c'"/>-->
      <!--      </el-icon>-->
    </div>
    <div class="ptz-cell ptz-right" @mousedown="ptzControl('right')" @mouseup="ptzControl('stop')"
         command="right" title="右">
      <el-icon>
        <ArrowRightBold/>
      </el-icon>
    </div>
    <!--    <div class="ptz-cell ptz-downleft" @mousedown="ptzControl('downleft')" @mouseup="ptzControl('stop')"-->
    <!--         command="downleft" title="右下">-->
    <!--      <el-icon>-->
    <!--        <ArrowDownBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <!--    <div class="ptz-cell ptz-downright" @mousedown="ptzControl('downright')" @mouseup="ptzControl('stop')"-->
    <!--         command="downright" title="左下">-->
    <!--      <el-icon>-->
    <!--        <ArrowDownBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <div class="ptz-cell ptz-down" @mousedown="ptzControl('down')" @mouseup="ptzControl('stop')"
         command="down" title="下">
      <el-icon>
        <ArrowDownBold/>
      </el-icon>
    </div>
    <div class="ptz-cell-f ptz-zoobox">
      <div @mousedown="ptzControl('zoomin')" @mouseup="ptzControl('stop')" command="zoomin" title="放大">
        <el-icon>
          <Plus/>
        </el-icon>
      </div>
      <div @mousedown="ptzControl('zoomout')" @mouseup="ptzControl('stop')" command="zoomout" title="缩小">
        <el-icon>
          <Minus/>
        </el-icon>
      </div>
    </div>
    <div class="ptz-slide">
      <el-slider v-model="speedValue" :max="255"/>
    </div>
  </div>
  <div class="qt-box">
    <p style="text-align: center">
      <el-button type="primary" @click="setLocation()">预置位设置</el-button>
    </p>
    <el-table :data="setLocationList" border style="width: 100%">
      <el-table-column prop="presetName" label="预置位名称" header-align="center" align="center"></el-table-column>
      <!--      <el-table-column prop="presetId" label="预置位ID" header-align="center" align="center"></el-table-column>-->
      <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150">
        <template v-slot="scope">
          <el-button type="primary" link @click="callLocation(scope.row.presetId)">调用</el-button>
          <el-button type="primary" link @click="deleteSetLocation(scope.row.presetId)">{{ $t("delete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div>
    <p style="text-align: center">
      <el-button type="primary" size="small" @click="routingInspection()">巡检设置</el-button>
      <el-button type="primary" size="small" @click="beginInspection()">开始巡检</el-button>
      <el-button type="primary" size="small" @click="stopInspection()">停止巡检</el-button>
    </p>
    <div>
    </div>
  </div>

  <RoutingInspectionView ref="routinginspectionview"></RoutingInspectionView>
</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import baseService from "@/service/baseService";
import Collects from "@/views/livegbs/collects.vue";
import {Top} from "@element-plus/icons-vue";
import app from "@/constants/app";
import {useAppStore} from "@/store";
import axios from "axios";
// import {tableRowClassName} from "@/utils/tableRowClassName.js";
import RoutingInspectionView from "@/views/videoviews/rightbox/routingInspectionView.vue"
import CryptoJS from "crypto-js";

export default {
  components: {Top, Collects, RoutingInspectionView},
  props: ['playerList', 'iWndType', 'audioData', 'cameraData'],
  data() {
    return {
      useAppStore,
      recorder: null,
      ws: null,
      level: 0,
      // 记录存储已登录音频ip
      control: false,
      speedValue: 150,
      setLocationList: [],
      // 音频信息
      strem: null,
      pc: null

    }
  },
  methods: {
    beginInspection() {
      if (this.cameraData.flvUrl === "") {
        return this.$message.warning("请先选择播放视频！");
      }
      axios.get(`${app.httpgb}/api/front-end/cruise/start/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}?cruiseId=1`, {
        headers: {
          'access-Token': this.useAppStore().state.accessToken
        }
      }).then((res) => {
        if (res.data.code === 0) {
          return this.$message.success("开始巡检");
        }
        this.$message.error(res.data.msg);
      }).catch((error) => {
        // this.$message.error(error.data.msg);
      });
    },
    stopInspection() {
      if (this.cameraData.flvUrl === "") {
        return this.$message.error("请先选择播放视频！");
      }
      axios.get(`${app.httpgb}/api/front-end/cruise/stop/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}?cruiseId=1`, {
        headers: {
          'access-Token': this.useAppStore().state.accessToken
        }
      }).then((res) => {
        if (res.data.code === 0) {
          return this.$message.success("已停止");
        }
        this.$message.error(res.data.msg);
      }).catch((error) => {
        // this.$message.error(error.data.msg);
      });
    },
    routingInspection() {
      if (this.cameraData.flvUrl === "") {
        return this.$message.warning("请先选择播放视频！");
      }
      this.$refs.routinginspectionview.init(this.setLocationList, this.cameraData);
    },
    getLocationList() {
      axios.get(`${app.httpgb}/api/front-end/preset/query/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}`, {
        headers: {
          'access-Token': this.useAppStore().state.accessToken
        }
      }).then((res) => {
        if (res.data.code === 0) {
          if (res.data.data === "获取设备预置位超时") {
            this.setLocationList = [];
            // this.$message.error(res.data.data);
          } else {
            this.setLocationList = res.data.data;
          }
          return
        }
      }).catch((error) => {
        this.setLocationList = [];
        // this.$message.error(error.data.msg);
      });
    },
    // 设置预置位
    setLocation() {
      if (this.cameraData.flvUrl === "") {
        return this.$message.warning("请先选择播放视频！");
      }
      ElMessageBox.prompt('预置位编号', '预置位设置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern:
            /^(?!0$)([1-9]\d{0,2}|1\d{2}|2[0-4]\d|25[0-5])$/,
        inputErrorMessage: '预置位编号只能为1~255的整数!',
      }).then(({value}) => {
        axios.get(`${app.httpgb}/api/front-end/preset/add/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}`, {
          params: {
            presetId: value
          },
          headers: {
            'access-Token': this.useAppStore().state.accessToken
          }
        }).then((res) => {
          if (res.data.code === 0) {
            this.getLocationList();
            return this.$message.success("设置成功！");
          }
          this.$message.error(res.data.msg);
        }).catch((error) => {
          // return this.$message.error(error.data.msg);
        });
      })
    },
    // 调用预置位
    callLocation(id) {
      axios.get(`${app.httpgb}/api/front-end/preset/call/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}`, {
        params: {
          presetId: id
        },
        headers: {
          'access-Token': this.useAppStore().state.accessToken
        }
      }).then((res) => {
        if (res.data.code === 0) {
          return this.$message.success("调用成功！");
        }
        this.$message.error(res.data.msg);
      }).catch((error) => {
        // return this.$message.error(error.data.msg);
      });
    },
    // 删除预置位
    deleteSetLocation(id) {
      axios.get(`${app.httpgb}/api/front-end/preset/delete/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}`, {
        params: {
          presetId: id
        },
        headers: {
          'access-Token': this.useAppStore().state.accessToken
        }
      }).then((res) => {
        if (res.data.code === 0) {
          this.getLocationList();
          return this.$message.success("删除成功！");
        }
        this.$message.error(res.data.msg);
      }).catch((error) => {
        this.$message.error(error.data.msg);
      });
    },
    // 控制
    ptzControl(command) {
      console.log(this.useAppStore().state)
      if (this.cameraData.flvUrl === "") {
        return this.$message.warning("请先选择播放视频！");
      }
      if (!this.cameraData.type.includes("ball")) {
        return ElMessage.warning("该相机不支持转动！");
      }
      let pamers = {
        command: command,
        horizonSpeed: this.speedValue,
        verticalSpeed: this.speedValue,
        zoomSpeed: 8
      }
      let token = this.useAppStore().state.accessToken;
      $.ajax({
        method: "GET",
        url: `${app.httpgb}/api/front-end/ptz/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}`,
        global: false,
        beforeSend: function (xhr) {
          xhr.setRequestHeader("access-Token", token);
        },
        data: pamers
      }).done(() => {
        this.$emit("liveNewData", this.cameraData, 0)
      }).fail(xhr => {
        if (xhr) {
        }
      })
    },
    // 单独 撤防 布防
    singledefensesetup(defen) {
      let id = this.cameraData.id;
      if (id === undefined) {
        ElMessage.error(" 该窗口暂无设备播放，请先选择设备！");
        return;
      }
      if (this.cameraData.type.includes("mn")) {
        ElMessage.warning(" 模拟相机不支持撤布防！");
        return;
      }
      if (defen) {
        baseService.post("Camera/kxcamera/setAlarmByIds", [id]).then(() => {
          ElMessage.success("布防成功！");
          this.$emit("defenhandle");
        });
      } else {
        baseService.post("Camera/kxcamera/outAlarmByIds", [id]).then(() => {
          ElMessage.success("撤防成功！");
          this.$emit("defenhandle");
        });
      }
    },
    // 集体 撤防 布防
    defensesetup(defen) {
      let id = this.cameraData.id;
      if (id === undefined) {
        ElMessage.error(" 该窗口暂无设备播放，请先选择设备！");
        return;
      }
      if (this.cameraData.type.includes("mn")) {
        ElMessage.warning(" 模拟相机不支持撤布防！");
        return;
      }
      if (defen) {
        baseService.post("Camera/kxcamera/setAlarmById?id=" + id).then(() => {
          ElMessage.success("布防成功！");
          this.$emit("defenhandle");
        });
      } else {
        baseService.post("Camera/kxcamera/outAlarmById?id=" + id).then(() => {
          ElMessage.success("撤防成功！");
          this.$emit("defenhandle");
        });
      }
    },
    openvocality() {
      this.$emit("openvocality", this.cameraData.idIndex)
    },
    closevocality() {
      this.$emit("closevocality", this.cameraData.idIndex)
    },
    talkStart() {
      const constraints = {
        audio: true
      };
      if (!navigator.mediaDevices.getUserMedia) {
        ElMessage.error("浏览器不支持音频输入!");
      } else {
        navigator.mediaDevices
            .getUserMedia(constraints)
            .then(async (mediaStream) => {
              this.strem = mediaStream;
              this.pc = new RTCPeerConnection();
              this.pc.addTransceiver("audio", {direction: "sendonly"});
              mediaStream.getTracks().forEach((track) => {
                this.pc.addTrack(track, mediaStream);
              });
              // 发送RTC请求
              const offer = await this.pc.createOffer();
              await this.pc.setLocalDescription(offer);

              this.ws = true;

              // 开启设备
              axios.get(`${app.httpgb}/api/play/broadcast/${this.cameraData.gbDeviceNo}/${this.cameraData.gbChannelNo}`, {
                params: {
                  timeout: 30,
                  broadcastMode: true
                },
                headers: {
                  'access-Token': this.useAppStore().state.accessToken
                }
              }).then((res) => {
                if (res.data.code === 0) {
                  // 获取pushKey
                  axios.post(`${app.httpgb}/api/user/userInfo`, null, {
                    headers: {
                      'access-Token': this.useAppStore().state.accessToken
                    }
                  }).then(async (res) => {
                    if (res.data.code === 0) {
                      // MD5加密pushKey => sign
                      const sign = CryptoJS.MD5(res.data.data.pushKey).toString();
                      // 连接RTC信令
                      const datas = await axios.post(`${app.webrtc}?app=broadcast&stream=${this.cameraData.gbDeviceNo}_${this.cameraData.gbChannelNo}&type=push&sign=${sign}`,
                          offer.sdp
                      );
                      await this.pc.setRemoteDescription(new RTCSessionDescription({
                        type: datas.data.type,
                        sdp: datas.data.sdp
                      }));
                      this.pc.onicecandidate = () => {
                        // 发送给信令服务器ICE信息
                      };
                      return
                    }
                    this.$message.error(res.data.msg);
                  }).catch((error) => {
                    this.$message.error(error.data.msg);
                  });
                  return
                }
                this.$message.error(res.data.msg);
              }).catch((error) => {
                this.$message.error(error.data.msg);
              });
            })
            .catch((error) => {
              switch (error.message || error.name) {
                case "PERMISSION_DENIED":
                case "PermissionDeniedError":
                  ElMessage.error("用户拒绝提供信息!");
                  break;
                case "NOT_SUPPORTED_ERROR":
                case "NotSupportedError":
                  ElMessage.error("浏览器不支持硬件设备!");
                  break;
                case "MANDATORY_UNSATISFIED_ERROR":
                case "MandatoryUnsatisfiedError":
                  ElMessage.error("无法发现指定的硬件设备!");
                  break;
                default:
                  console.log(error)
                  ElMessage.error("无法打开麦克风。异常信息:" + (error.code || error.name));
                  break;
              }
            });
      }
    },
    // 关闭麦克风
    talkStop() {
      this.ws = false;
      if (this.strem) {
        this.strem.getTracks().forEach((track) => track.stop());
      }
      if (this.pc) {
        this.pc.close();
      }
    }
  }
}
</script>


<style scoped lang="scss">
.qt-box {
  padding: 50px 20px 0 20px;
}

.mic-level-bar {
  position: absolute;
  transform: rotate(-90deg);
  width: 100%;
  top: 70px;
  left: -80px;
}

.ptz-slide {
  padding-top: 180px;
  width: 200px;
  margin: auto;
}

.ptz-block {
  width: 100%;
  position: relative;
  font-size: 24px;
  top: 40px;

  .ptz-cell {
    width: 50px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
  }

  .ptz-cell-f {
    width: 50px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;

    div:hover {
      color: #51f32d;
    }
  }

  .ptz-cell.active {
    color: #ccc;
    font-size: 26px;
  }

  .ptz-cell.readonly {
    color: #ddd;
  }

  .ptz-cell:hover {
    color: #51f32d;
  }

  .fa-microphone, .fa-microphone-slash {
    padding: 10px 13px;
    border-radius: 25px;
  }

  .fa-microphone.active {
    color: #FFF;
  }

  .fa-microphone.readonly {
    color: #ddd;
  }

  .fa-microphone-slash.readonly {
    color: #ddd;
  }

  .mic-level-bar {
    position: absolute;
    transform: rotate(-90deg);
    width: 70%;
    top: 80px;
    left: -50px;
  }

  .ptz-center {
    width: 50px;
    height: 50px;
    position: absolute;
    top: 40px;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 50%;
    background-color: #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .ptz-up {
    top: 0;
    left: 50%;
    transform: translateX(-50%);
  }

  .ptz-upright {
    top: 15px;
    left: 55%;
    transform: rotate(45deg);
  }

  .ptz-upleft {
    top: 15px;
    left: 22%;
    transform: rotate(-45deg);
  }

  .ptz-left {
    top: 40px;
    left: 32%;
    transform: translateX(-50%);
  }

  .ptz-right {
    top: 40px;
    left: 68%;
    transform: translateX(-50%);
  }

  .ptz-downleft {
    top: 85px;
    left: 22%;
    transform: rotate(45deg);
  }

  .ptz-downright {
    top: 85px;
    left: 55%;
    transform: rotate(-45deg);
  }

  .ptz-down {
    top: 80px;
    left: 50%;
    transform: translateX(-50%);
  }

  .ptz-zoobox {
    width: 40%;
    top: 130px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: space-between;
  }


  //.ptz-up,
  //.ptz-left,
  //.ptz-right,
  //.ptz-down,
  //.ptz-center > .fa-microphone,
  //.ptz-zoomin,
  //.ptz-talk > .fa-microphone,
  //.ptz-zoomout {
  //  cursor: pointer;
  //  &.readonly {
  //    cursor: auto;
  //  }
  //}
}

</style>
